import { DataSource, DataSourceOptions } from 'typeorm'
import { app } from 'electron'
import path from 'path'
import { log } from '../services/logger'
import { Project } from './entities/Project'
// 其他实体导入可以在这里添加

let dataSource: DataSource | null = null

/**
 * 数据库配置
 */
const getDatabaseConfig = (): DataSourceOptions => {
  const dbPath = path.join(app.getPath('userData'), 'database.sqlite')
  
  return {
    type: 'better-sqlite3',
    database: dbPath,
    entities: [Project], // 添加其他实体
    synchronize: process.env.NODE_ENV === 'development', // 生产环境应使用迁移
    logging: process.env.NODE_ENV === 'development' ? ['query', 'error'] : ['error'],
    // 连接池配置
    extra: {
      // better-sqlite3 特定配置
      verbose: process.env.NODE_ENV === 'development' ? console.log : undefined,
      // 启用WAL模式提高并发性能
      pragma: {
        journal_mode: 'WAL',
        synchronous: 'NORMAL',
        cache_size: -64000, // 64MB缓存
        temp_store: 'MEMORY',
        mmap_size: 268435456, // 256MB内存映射
      }
    },
    // 迁移配置
    migrations: [path.join(__dirname, 'migrations', '*.ts')],
    migrationsRun: true, // 自动运行迁移
    migrationsTableName: 'spf_migrations'
  }
}

/**
 * 获取数据库连接
 */
export async function getDataSource(): Promise<DataSource> {
  if (dataSource && dataSource.isInitialized) {
    return dataSource
  }

  const config = getDatabaseConfig()
  dataSource = new DataSource(config)

  try {
    const startTime = performance.now()
    await dataSource.initialize()
    const endTime = performance.now()
    
    log.performance('数据库连接初始化', endTime - startTime)
    log.database('数据库连接已建立', undefined, {
      database: config.database,
      entities: config.entities?.length || 0
    })
    
    return dataSource
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error)
    const errorStack = error instanceof Error ? error.stack : undefined
    log.error('数据库连接初始化失败', {
      error: errorMessage,
      stack: errorStack,
      config: { ...config, database: path.basename(config.database as string) }
    })
    throw error
  }
}

/**
 * 关闭数据库连接
 */
export async function closeDataSource(): Promise<void> {
  if (dataSource && dataSource.isInitialized) {
    try {
      await dataSource.destroy()
      dataSource = null
      log.database('数据库连接已关闭')
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error)
      log.error('关闭数据库连接失败', { error: errorMessage })
      throw error
    }
  }
}

/**
 * 检查数据库连接状态
 */
export function isDatabaseConnected(): boolean {
  return dataSource !== null && dataSource.isInitialized
}

/**
 * 获取数据库统计信息
 */
export async function getDatabaseStats(): Promise<{
  isConnected: boolean
  entityCount: number
  migrationCount: number
  lastMigration?: string
}> {
  if (!isDatabaseConnected()) {
    return {
      isConnected: false,
      entityCount: 0,
      migrationCount: 0
    }
  }

  try {
    const ds = await getDataSource()
    const migrations = await ds.showMigrations()
    const migrationArray = Array.isArray(migrations) ? migrations : []
    const lastMigration = migrationArray.length > 0 ? migrationArray[migrationArray.length - 1].name : undefined

    return {
      isConnected: true,
      entityCount: ds.entityMetadatas.length,
      migrationCount: migrationArray.length,
      lastMigration
    }
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error)
    log.error('获取数据库统计信息失败', { error: errorMessage })
    return {
      isConnected: false,
      entityCount: 0,
      migrationCount: 0
    }
  }
}

/**
 * 执行数据库健康检查
 */
export async function healthCheck(): Promise<boolean> {
  try {
    if (!isDatabaseConnected()) {
      return false
    }

    const ds = await getDataSource()
    // 执行简单查询测试连接
    await ds.query('SELECT 1')
    
    log.database('数据库健康检查通过')
    return true
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error)
    log.error('数据库健康检查失败', { error: errorMessage })
    return false
  }
}

// 应用退出时自动关闭连接
app.on('before-quit', async () => {
  await closeDataSource()
})

// 导出默认数据源获取函数
export default getDataSource
